package constant.milk.periodapp.info;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import constant.milk.periodapp.R;
import constant.milk.periodapp.SuperActivity;
import constant.milk.periodapp.alarm.MilkAlarm;
import constant.milk.periodapp.bean.SengriData;
import constant.milk.periodapp.database.DBSelectQuery;
import constant.milk.periodapp.database.DbDeleteQuery;
import constant.milk.periodapp.database.DbUpdateQuery;
import constant.milk.periodapp.dialog.MilkCountDialog;
import constant.milk.periodapp.dialog.MilkCountDialog.CountCallBack;
import constant.milk.periodapp.dialog.MilkYesNoDialog;
import constant.milk.periodapp.util.MilkShared;
import constant.milk.periodapp.util.MilkUtil;

public class InfoActivity extends SuperActivity
{
	public static final String INFO_YEAR = "INFO_YEAR";
	
	private TextView backTextView;
	
	private TextView sengriDateTextView;
	private TextView sengriTermTextView;
	
	private TextView preTextView;
	private TextView nextTextView;
	private TextView yearTextView;
	
	private ListView listView;
	
	private DBSelectQuery select;
	
	private Calendar cal;
	
	private PopupWindow pw;
	
	private View updateView;
	private View deleteView;
	
	private int sengriId;
	
	private MilkYesNoDialog yesNoDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.info_activity);
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		backTextView = (TextView) findViewById(R.id.infoBackTextView);
		
		sengriDateTextView = (TextView) findViewById(R.id.infoDateTextView);
		sengriTermTextView = (TextView) findViewById(R.id.infoTermTextView);
		
		preTextView = (TextView) findViewById(R.id.infoPreTextView);
		nextTextView = (TextView) findViewById(R.id.infoNextTextView);
		yearTextView = (TextView) findViewById(R.id.infoYearTextView);
		
		listView = (ListView) findViewById(R.id.infoListView);
	}

	@Override
	protected void setOnClick()
	{
		backTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		
		preTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				int termAverage = select.getSengriTermAverage();
				
				sengriDateTextView.setText(termAverage + "일");
				
				sengriTermTextView.setText(MilkUtil.getAveSengriTerm(superContext, select) + "일");
				
				cal.add(Calendar.YEAR, -1);
				yearTextView.setText(cal.get(Calendar.YEAR) + "");
				ArrayList<SengriData> list = select.getSengriListYear(cal.get(Calendar.YEAR));
				SengriAdapter adapter = new SengriAdapter(superContext, R.layout.list_item_info, list);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
			}
		});
		
		nextTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				int termAverage = select.getSengriTermAverage();
				
				sengriDateTextView.setText(termAverage + "일");
				
				sengriTermTextView.setText(MilkUtil.getAveSengriTerm(superContext, select) + "일");
				
				cal.add(Calendar.YEAR, 1);
				yearTextView.setText(cal.get(Calendar.YEAR) + "");
				ArrayList<SengriData> list = select.getSengriListYear(cal.get(Calendar.YEAR));
				SengriAdapter adapter = new SengriAdapter(superContext, R.layout.list_item_info, list);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
			}
		});
	}

	@Override
	protected void setData()
	{
		cal = Calendar.getInstance();
		
		Intent intent = getIntent();
		int year = intent.getIntExtra(INFO_YEAR, cal.get(Calendar.YEAR));
		
		cal.set(Calendar.YEAR, year);
		
		select = new DBSelectQuery(superContext, superDb);
		
		int termAverage = select.getSengriTermAverage();
		
		sengriDateTextView.setText(termAverage + "일");
		
		sengriTermTextView.setText(MilkUtil.getAveSengriTerm(superContext, select) + "일");
		
		yearTextView.setText(cal.get(Calendar.YEAR) + "");
		
		listView.setOnItemClickListener(oicl);
		ArrayList<SengriData> list = select.getSengriListYear(cal.get(Calendar.YEAR));
		SengriAdapter adapter = new SengriAdapter(superContext, R.layout.list_item_info, list);
		listView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		
		setPopWindow();
	}
	
	private void setPopWindow()
	{
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.popup_window_info, null);
		
		pw = new PopupWindow(v);
		pw.setWindowLayoutMode(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		pw.setOutsideTouchable(true);
		pw.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_white));
		
		updateView = v.findViewById(R.id.popupInfoUpdateView);
		deleteView = v.findViewById(R.id.popupInfoDeleteView);
		
		updateView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				pw.dismiss();
				
				SengriData data = select.getSengriId(sengriId);
				
				MilkCountDialog dialog = new MilkCountDialog(superContext, "생리기간",
						new CountCallBack()
				{
					@Override
					public void getCount(int count)
					{
						if (setPeriodUpdate(sengriId, count))
						{
							MilkUtil.showToast(superContext, "생리기간 수정에 성공하였습니다.");
							
							int termAverage = select.getSengriTermAverage();
							
							sengriDateTextView.setText(termAverage + "일");
							
							sengriTermTextView.setText(MilkUtil.getAveSengriTerm(superContext, select) + "일");
							
							listView.setOnItemClickListener(oicl);
							ArrayList<SengriData> list = select.getSengriListYear(cal.get(Calendar.YEAR));
							SengriAdapter adapter = new SengriAdapter(superContext, R.layout.list_item_info, list);
							listView.setAdapter(adapter);
							
							setResult(Activity.RESULT_OK);
						}
						else
						{
							MilkUtil.showToast(superContext, "수정 실패! 개발자에게 문의해주세요.");
						}
					}
				}, data.getTerm());
				
				dialog.show();
			}
		});
		
		deleteView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				pw.dismiss();
				
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "생리일을 삭제 하시겠습니까?", new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						if (setDeleteData(sengriId))
						{
							MilkAlarm ma = new MilkAlarm();
							ma.checkAlarm(superContext, superDb);
							MilkUtil.showToast(superContext, "생리일 삭제에 성공하였습니다.");
							
							int termAverage = select.getSengriTermAverage();
							
							sengriDateTextView.setText(termAverage + "일");
							
							sengriTermTextView.setText(MilkUtil.getAveSengriTerm(superContext, select) + "일");
							
							listView.setOnItemClickListener(oicl);
							ArrayList<SengriData> list = select.getSengriListYear(cal.get(Calendar.YEAR));
							SengriAdapter adapter = new SengriAdapter(superContext, R.layout.list_item_info, list);
							listView.setAdapter(adapter);
							
							setResult(Activity.RESULT_OK);
						}
						else
						{
							MilkUtil.showToast(superContext, "삭제 실패! 개발자에게 문의해주세요.");
						}
						
						yesNoDialog.dismiss();
					}
				});
				
				yesNoDialog.show();
			}
		});
	}
	
	private OnItemClickListener oicl = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id)
		{
			SengriData data = (SengriData) parent.getItemAtPosition(position);
			sengriId = data.getId();
			pw.showAsDropDown(view);
		}
	};
	
	private boolean setPeriodUpdate(int id, int term)
	{
		DbUpdateQuery query = null;
		
		try
		{
			query = new DbUpdateQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			if (term == -1)
			{
				MilkShared s = new MilkShared(superContext);
				term = s.getSengriDate();
			}
			
			map.put("term", term + "");
			
			query.setPeriodUpdate(id, map);
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setDeleteData(int id)
	{
		DbDeleteQuery query = null;
		
		try
		{
			query = new DbDeleteQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			query.setPeriodDelete(id);
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	@Override
	public void onBackPressed()
	{
		if (pw.isShowing())
		{
			pw.dismiss();
			return;
		}
		
		super.onBackPressed();
	}
	
	private class SengriAdapter extends ArrayAdapter<SengriData>
	{
		public SengriAdapter(Context context, int resource,
				List<SengriData> objects)
		{
			super(context, resource, objects);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.list_item_info, null);
			}
			
			SengriData data = getItem(position);
			
			TextView startTextView = (TextView) v.findViewById(R.id.listItemStartTextView);
			TextView endTextView = (TextView) v.findViewById(R.id.listItemEndTextView);
			TextView termTextView = (TextView) v.findViewById(R.id.listItemTermTextView);
			
			Calendar cal = Calendar.getInstance();
			cal.set(data.getYear(), data.getMonth(), data.getDay());
			
			startTextView.setText(MilkUtil.getMonthDay(cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH)));
			
			termTextView.setText(data.getTerm() + "일");
			
			Calendar cal2 = Calendar.getInstance();
			cal2.set(data.getYear(), data.getMonth(), data.getDay());
			cal2.add(Calendar.DAY_OF_MONTH, data.getTerm()-1);
			
			endTextView.setText(MilkUtil.getMonthDay(cal2.get(Calendar.MONTH)+1, cal2.get(Calendar.DAY_OF_MONTH)));
			
			return v;
		}
	}
}
